package dsregistry

type RegistryStats struct {
	Env            string                    `json:"env"`            // 当前环境名称
	ServiceCount   int                       `json:"serviceCount"`   // 服务数量
	InstanceCounts map[string]int            `json:"instanceCounts"` // serviceName -> 实例数量
	InstanceStatus map[string]map[string]int `json:"instanceStatus"` // serviceName -> {UP, DOWN, OUT_OF_SERVICE}
	RedisConnected bool                      `json:"redisConnected"` // Redis 是否连接成功
}

func (r *RedisRegistry) Stats() RegistryStats {
	stats := RegistryStats{
		Env:            r.env,
		InstanceCounts: make(map[string]int),
		InstanceStatus: make(map[string]map[string]int),
	}

	r.cacheLock.RLock()
	defer r.cacheLock.RUnlock()

	stats.ServiceCount = len(r.serviceCache)

	for name, instances := range r.serviceCache {
		stats.InstanceCounts[name] = len(instances)

		statusMap := map[string]int{
			StatusUp:           0,
			StatusDown:         0,
			StatusOutOfService: 0,
		}

		for _, inst := range instances {
			statusMap[inst.Status]++
		}

		stats.InstanceStatus[name] = statusMap
	}

	// 检测 Redis 连接状态
	_, err := r.client.Ping(r.ctx).Result()
	stats.RedisConnected = err == nil

	return stats
}
